package lk.icta.core.web.action;

import lk.icta.common.AppConstants;
import lk.icta.common.web.WebConstants;
import lk.icta.common.web.action.BaseAction;
import lk.icta.user.common.AuthorizationException;
import lk.icta.user.entity.User;
import lk.icta.user.service.UserManager;
import org.apache.struts2.interceptor.SessionAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Locale;

public class LoginAction extends BaseAction {

    private static final Logger logger = LoggerFactory.getLogger(LoginAction.class);

    private String username;
    private String password;
    private final UserManager userManager;
    private String prefLanguage;
    private int androidApp;  // androidApp == 1 for Android App

    public LoginAction(UserManager userManager) {
        this.userManager = userManager;
    }

    public Locale getLocale() {
        return (Locale) session.get(WebConstants.SESSION_USER_LANG);
    }

    public String welcome() {
        logger.debug("Welcome");
        return SUCCESS;
    }

    public String login() {
        logger.debug("User Login");
        try {
            user = userManager.authenticateUser(username, userManager.hashPassword(password));
            logger.debug("isAndroid ", androidApp);

            if (androidApp == 1) {
                user.setUserDevice(AppConstants.ANDROID);
            } else {
                user.setUserDevice(AppConstants.OTHER);
            }

            logger.debug("user androidApp .... {}", getUser().getUserDevice());

            session.put(AppConstants.SESSION_USER_GROUP, user.getRole().getId().toLowerCase());
            session.put(AppConstants.SESSION_USER_BEAN, user);

            String language = user.getPrefLanguage();
            //TODO: to be removed language from the session
            String country = "LK";
            session.put(WebConstants.SESSION_USER_LANG, new Locale(language, country));

            if (user.getLoginState() != User.LoginState.NORMAL) {
                prefLanguage = user.getPrefLanguage();
                return "firstLogin";

            } else if (user.getRole().getId().equals(AppConstants.SLC_USER_ROLE)) {
                prefLanguage = user.getPrefLanguage();
                return "slcUser";
            }

            findLocation();

            return SUCCESS;
        } catch (AuthorizationException e) {
            e.printStackTrace();
            addActionError("Invalid Username or Password!");
            return ERROR;
        } catch (Exception ex) {
            ex.printStackTrace();
            addActionError("Invalid Login!");
            return ERROR;
        }
    }

    public String logout() {
        /* if there is a logged user */
        try {
            if (session.containsKey(AppConstants.SESSION_USER_BEAN)) {
                session.put(AppConstants.SESSION_USER_GROUP, null);
                session.put(AppConstants.SESSION_USER_BEAN, null);
                session.put(AppConstants.SESSION_USER_DEVICE, null);
                session.put(WebConstants.SESSION_USER_LANG, null);
                if (session instanceof org.apache.struts2.dispatcher.SessionMap) {
                    try {
                        ((org.apache.struts2.dispatcher.SessionMap) session).invalidate();
                        logger.debug("Session invalidated");
                    } catch (IllegalStateException e) {
                        logger.error("Incorrect Session", e);
                    }
                }
            }

            user = null;
            session = null;
            language = null;
            userProvinceId = -1;
            userDistrictId = -1;
            userBranchId = -1;
            return SUCCESS;
        } catch (Exception e) {
            user = null;
            session = null;
            language = null;
            userProvinceId = -1;
            userDistrictId = -1;
            userBranchId = -1;
            e.printStackTrace();
            return ERROR;
        }
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPrefLanguage() {
        return prefLanguage;
    }

    public void setPrefLanguage(String prefLanguage) {
        this.prefLanguage = prefLanguage;
    }

    public int getAndroidApp() {
        return androidApp;
    }

    public void setAndroidApp(int androidApp) {
        this.androidApp = androidApp;
    }
}
